import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/song.dart';
import '../providers/music_provider.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchFocusNode = FocusNode();
  List<Song> _searchResults = [];
  List<String> _recentSearches = [];
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    _loadRecentSearches();
  }

  @override
  void dispose() {
    _searchController.dispose();
    _searchFocusNode.dispose();
    super.dispose();
  }

  void _loadRecentSearches() {
    // TODO: 从本地存储加载最近搜索
    _recentSearches = [
      '周杰伦',
      'Faded',
      '告白气球',
      '阳光开朗大男孩',
    ];
  }

  void _performSearch(String query, MusicProvider musicProvider) async {
    if (query.trim().isEmpty) {
      setState(() {
        _searchResults = [];
        _isSearching = false;
      });
      return;
    }

    setState(() {
      _isSearching = true;
    });

    // 添加到最近搜索
    _addToRecentSearches(query);

    try {
      final results = await musicProvider.musicScannerService.searchSongs(query);
      setState(() {
        _searchResults = results;
        _isSearching = false;
      });
    } catch (e) {
      setState(() {
        _searchResults = [];
        _isSearching = false;
      });
    }
  }

  void _addToRecentSearches(String query) {
    setState(() {
      _recentSearches.removeWhere((item) => item.toLowerCase() == query.toLowerCase());
      _recentSearches.insert(0, query);
      if (_recentSearches.length > 10) {
        _recentSearches.removeLast();
      }
    });
    // TODO: 保存到本地存储
  }

  void _clearRecentSearches() {
    setState(() {
      _recentSearches.clear();
    });
    // TODO: 从本地存储删除
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('搜索音乐'),
        elevation: 0,
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(60),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: _buildSearchBar(),
          ),
        ),
      ),
      body: Consumer<MusicProvider>(
        builder: (context, musicProvider, child) {
          return Column(
            children: [
              if (_searchController.text.isEmpty && !_isSearching)
                Expanded(child: _buildRecentSearches())
              else if (_isSearching)
                const Expanded(
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircularProgressIndicator(),
                        SizedBox(height: 16),
                        Text('正在搜索...'),
                      ],
                    ),
                  ),
                )
              else if (_searchResults.isEmpty && _searchController.text.isNotEmpty)
                Expanded(child: _buildNoResults())
              else
                Expanded(child: _buildSearchResults(musicProvider)),
            ],
          );
        },
      ),
    );
  }

  Widget _buildSearchBar() {
    return Container(
      height: 44,
      decoration: BoxDecoration(
        color: Theme.of(context).cardColor,
        borderRadius: BorderRadius.circular(22),
        border: Border.all(
          color: Colors.grey.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: TextField(
        controller: _searchController,
        focusNode: _searchFocusNode,
        decoration: InputDecoration(
          hintText: '搜索歌曲、艺术家、专辑',
          prefixIcon: const Icon(Icons.search, color: Colors.grey),
          suffixIcon: _searchController.text.isNotEmpty
              ? IconButton(
                  icon: const Icon(Icons.clear, color: Colors.grey),
                  onPressed: () {
                    _searchController.clear();
                    setState(() {
                      _searchResults = [];
                    });
                  },
                )
              : null,
          border: InputBorder.none,
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 16,
            vertical: 12,
          ),
        ),
        onChanged: (value) {
          setState(() {});
          if (value.trim().isNotEmpty) {
            // 延迟搜索，避免频繁调用
            Future.delayed(const Duration(milliseconds: 500), () {
              if (_searchController.text == value && mounted) {
                final musicProvider = Provider.of<MusicProvider>(context, listen: false);
                _performSearch(value, musicProvider);
              }
            });
          }
        },
        onSubmitted: (value) {
          final musicProvider = Provider.of<MusicProvider>(context, listen: false);
          _performSearch(value, musicProvider);
        },
      ),
    );
  }

  Widget _buildRecentSearches() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 热门搜索
          _buildHotSearches(),
          
          const SizedBox(height: 24),
          
          // 最近搜索
          if (_recentSearches.isNotEmpty) ...[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '最近搜索',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                TextButton(
                  onPressed: _clearRecentSearches,
                  child: const Text('清空'),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _recentSearches.map((search) {
                return GestureDetector(
                  onTap: () {
                    _searchController.text = search;
                    final musicProvider = Provider.of<MusicProvider>(context, listen: false);
                    _performSearch(search, musicProvider);
                  },
                  child: Chip(
                    label: Text(search),
                    onDeleted: () {
                      setState(() {
                        _recentSearches.remove(search);
                      });
                    },
                    deleteIcon: const Icon(Icons.close, size: 16),
                  ),
                );
              }).toList(),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildHotSearches() {
    final hotSearches = ['周杰伦', 'Alan Walker', 'Ed Sheeran', 'Adele', '告白气球', 'Faded'];
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '热门搜索',
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: hotSearches.asMap().entries.map((entry) {
            final index = entry.key;
            final search = entry.value;
            final isTop3 = index < 3;
            
            return GestureDetector(
              onTap: () {
                _searchController.text = search;
                final musicProvider = Provider.of<MusicProvider>(context, listen: false);
                _performSearch(search, musicProvider);
              },
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: isTop3 
                      ? Theme.of(context).primaryColor.withOpacity(0.1)
                      : Theme.of(context).cardColor,
                  borderRadius: BorderRadius.circular(16),
                  border: Border.all(
                    color: isTop3 
                        ? Theme.of(context).primaryColor.withOpacity(0.3)
                        : Colors.grey.withOpacity(0.3),
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 16,
                      height: 16,
                      decoration: BoxDecoration(
                        color: isTop3 ? Theme.of(context).primaryColor : Colors.grey,
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                        child: Text(
                          '${index + 1}',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 10,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      search,
                      style: TextStyle(
                        color: isTop3 ? Theme.of(context).primaryColor : null,
                        fontWeight: isTop3 ? FontWeight.bold : null,
                      ),
                    ),
                  ],
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }

  Widget _buildSearchResults(MusicProvider musicProvider) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              Text(
                '找到 ${_searchResults.length} 首歌曲',
                style: Theme.of(context).textTheme.titleMedium,
              ),
              const Spacer(),
              if (_searchResults.isNotEmpty)
                TextButton.icon(
                  onPressed: () {
                    // 播放所有搜索结果
                    musicProvider.setPlaylist(_searchResults);
                    musicProvider.playSong(_searchResults.first);
                  },
                  icon: const Icon(Icons.play_arrow),
                  label: const Text('播放全部'),
                ),
            ],
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _searchResults.length,
            itemBuilder: (context, index) {
              final song = _searchResults[index];
              final isCurrentSong = musicProvider.currentSong?.id == song.id;
              
              return ListTile(
                leading: Container(
                  width: 48,
                  height: 48,
                  decoration: BoxDecoration(
                    color: Theme.of(context).primaryColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(
                    isCurrentSong ? Icons.music_note : Icons.music_note_outlined,
                    color: isCurrentSong 
                        ? Theme.of(context).primaryColor 
                        : Colors.grey,
                  ),
                ),
                title: RichText(
                  text: TextSpan(
                    style: DefaultTextStyle.of(context).style,
                    children: _highlightSearchTerm(
                      song.name,
                      _searchController.text,
                      isCurrentSong,
                    ),
                  ),
                ),
                subtitle: RichText(
                  text: TextSpan(
                    style: const TextStyle(color: Colors.grey),
                    children: _highlightSearchTerm(
                      '${song.artist} • ${song.album}',
                      _searchController.text,
                      false,
                    ),
                  ),
                ),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      song.duration,
                      style: const TextStyle(color: Colors.grey, fontSize: 12),
                    ),
                    const SizedBox(width: 8),
                    if (isCurrentSong && musicProvider.isPlaying)
                      Icon(
                        Icons.volume_up,
                        color: Theme.of(context).primaryColor,
                        size: 20,
                      ),
                    PopupMenuButton<String>(
                      icon: const Icon(Icons.more_vert, size: 20),
                      onSelected: (value) {
                        switch (value) {
                          case 'play_next':
                            // TODO: 下一首播放
                            break;
                          case 'add_to_playlist':
                            // TODO: 添加到播放列表
                            break;
                          case 'favorite':
                            // TODO: 收藏
                            break;
                        }
                      },
                      itemBuilder: (context) => [
                        const PopupMenuItem(
                          value: 'play_next',
                          child: ListTile(
                            leading: Icon(Icons.skip_next),
                            title: Text('下一首播放'),
                            contentPadding: EdgeInsets.zero,
                          ),
                        ),
                        const PopupMenuItem(
                          value: 'add_to_playlist',
                          child: ListTile(
                            leading: Icon(Icons.playlist_add),
                            title: Text('添加到播放列表'),
                            contentPadding: EdgeInsets.zero,
                          ),
                        ),
                        const PopupMenuItem(
                          value: 'favorite',
                          child: ListTile(
                            leading: Icon(Icons.favorite_border),
                            title: Text('收藏'),
                            contentPadding: EdgeInsets.zero,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                onTap: () {
                  musicProvider.playSong(song);
                },
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildNoResults() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.search_off,
            size: 80,
            color: Colors.grey.withOpacity(0.5),
          ),
          const SizedBox(height: 16),
          Text(
            '没有找到相关音乐',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '尝试使用其他关键词搜索',
            style: TextStyle(
              color: Colors.grey.withOpacity(0.7),
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  List<TextSpan> _highlightSearchTerm(String text, String searchTerm, bool isCurrentSong) {
    if (searchTerm.isEmpty) {
      return [
        TextSpan(
          text: text,
          style: TextStyle(
            color: isCurrentSong ? Theme.of(context).primaryColor : null,
            fontWeight: isCurrentSong ? FontWeight.bold : null,
          ),
        ),
      ];
    }

    final List<TextSpan> spans = [];
    final String lowerText = text.toLowerCase();
    final String lowerSearchTerm = searchTerm.toLowerCase();
    
    int start = 0;
    int index = lowerText.indexOf(lowerSearchTerm);
    
    while (index != -1) {
      // 添加高亮前的文本
      if (index > start) {
        spans.add(TextSpan(
          text: text.substring(start, index),
          style: TextStyle(
            color: isCurrentSong ? Theme.of(context).primaryColor : null,
            fontWeight: isCurrentSong ? FontWeight.bold : null,
          ),
        ));
      }
      
      // 添加高亮的文本
      spans.add(TextSpan(
        text: text.substring(index, index + searchTerm.length),
        style: TextStyle(
          color: Theme.of(context).primaryColor,
          fontWeight: FontWeight.bold,
          backgroundColor: Theme.of(context).primaryColor.withOpacity(0.2),
        ),
      ));
      
      start = index + searchTerm.length;
      index = lowerText.indexOf(lowerSearchTerm, start);
    }
    
    // 添加剩余的文本
    if (start < text.length) {
      spans.add(TextSpan(
        text: text.substring(start),
        style: TextStyle(
          color: isCurrentSong ? Theme.of(context).primaryColor : null,
          fontWeight: isCurrentSong ? FontWeight.bold : null,
        ),
      ));
    }
    
    return spans;
  }
} 